package elven.d.common.queue.sample.print;

import java.util.concurrent.LinkedBlockingQueue;

import elven.d.common.log.LogFactory;

public class Printer {
	
	private volatile static LinkedBlockingQueue<PrinterPreducer> preducers = new LinkedBlockingQueue<PrinterPreducer>();
	private volatile static Printer instance;
	private Printer() {}
	
	public static Printer getInstance(){
		if(instance == null){
			synchronized (preducers) {
				if(instance == null){
					instance = new Printer();
				}
			}
		}
		return instance;
	}

	public void print(){
		try {
			while(true){
				synchronized (preducers) {
					preducers.take().start();
				}
			}
		} catch (InterruptedException e) {
			LogFactory.d().error(e.getMessage(), e);
		}
	}
	
	public void setToPrint(String text){
		try {
			preducers.put(new PrinterPreducer(text));
		} catch (InterruptedException e) {
			LogFactory.d().error(e.getMessage(), e);
		}
	}
	
	public void setToPrint(String[] texts){
		try {
			for(int i = 0; i < texts.length; i++){
				preducers.put(new PrinterPreducer(texts[i]));
			}
			new PrinterConsumer(preducers).start();
		} catch (InterruptedException e) {
			LogFactory.d().error(e.getMessage(), e);
		}
	}
	
}
